package com.github.binarywang.demo.wx.mp.controller;

import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * jsapi 演示接口的 controller.
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 * @date 2020-04-25
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/jsapi/{appid}")
public class WxJsapiController {
    private final WxMpService wxService;

    @GetMapping("/getJsapiTicket")
    public String getJsapiTicket(@PathVariable String appid) throws WxErrorException {
        final WxJsapiSignature jsapiSignature = this.wxService.switchoverTo(appid).createJsapiSignature("111");
        System.out.println(jsapiSignature);
        return this.wxService.getJsapiTicket(true);
    }

    /**
     * 发送模板消息
     *
     * @param reqMap 包含所需参数的集合
     * @return 响应结果
     */
    @PostMapping("/tem-msg")
    public String sendTemplateMsg(@RequestBody Map<String, String> reqMap) throws WxErrorException {
        String temId = reqMap.get("temId");
        String redirectUri = reqMap.get("redirectUri");
        String openId = reqMap.get("openId");
        WxMpTemplateMsgService templateMsgService = wxService.getTemplateMsgService();
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.setToUser(openId);
        wxMpTemplateMessage.setTemplateId(temId);
        wxMpTemplateMessage.setUrl(redirectUri);

//        List<WxMpTemplateData> data = new ArrayList<>();
//        data.add(new WxMpTemplateData("孙武", "核酸检测报告", "#173177"));
//        data.add(new WxMpTemplateData());
//        data.add(new WxMpTemplateData());

        String res = templateMsgService.sendTemplateMsg(wxMpTemplateMessage);
        System.out.println("res = " + res);
        return res;
    }

}
